package app.gui;

import static cluster.Duster.Relation.isChildOf;
import static cluster.Duster.Relation.same;

import java.util.ArrayList;
import java.util.Iterator;

import processing.core.PApplet;

import app.ClusterApp;

import cluster.Duster;
import cluster.Duster.Relation;
import color.Color;

public class MouseDragger implements Interactive{
	int currentCluster = 0;
	ArrayList<Duster<Color>> selected;
	ClusterApp app;
	
	
	public MouseDragger(ClusterApp app) {
		super();
		this.app = app;
	}

	public void mousePressed(PApplet pa){
		if(app.clusters.size() <= currentCluster){
			clearSelection();
			return;
		}
		Duster<Color> d = app.clusters.get(0).root.contains(app.mouseX, app.mouseY);
		if(d == null) return;
		if(app.key != app.CODED) 
			if(app.key != app.SHIFT)
				clearSelection();
		if(d.selected) deselect(d);
		else select(d);
	}
	
	boolean isDragging;
	float dragX, dragY;
	public void mouseDragged(PApplet pa){
		if(selected == null) return;
		if(!isDragging){
			Iterator<Duster<Color>> i = selected.iterator();
			while(i.hasNext()){
				Duster<Color> next = i.next();
				Duster<Color> cont = next.contains(app.mouseX, app.mouseY);
				if(cont != null)
					if(cont.getID() == next.getID()){
						isDragging = true;
						dragX = app.mouseX;
						dragY = app.mouseY;
					}
			}
		}
	}
	
	public void select(Duster<Color> d){
		if(selected == null) selected = new ArrayList<Duster<Color>>(); 
		d.selected = true;
		selected.add(d);
	}
	
	public void deselect(Duster<Color> d){
		d.selected = false;
		if(selected != null) return;selected.remove(d);
	}
	
	public void clearSelection(){
		if(selected == null) return;
		Iterator<Duster<Color>> i = selected.iterator();
		while(i.hasNext()) i.next().selected = false;
		selected = null;
	}
	
	public void mouseReleased(PApplet pa){
		if(!isDragging) return;
		Duster<Color> d = app.clusters.get(0).root.contains(app.mouseX, app.mouseY);
		if(d == null) return;
		if(selected == null) return;
		Iterator<Duster<Color>> i = selected.iterator();
		while(i.hasNext()){
			Duster<Color> next = i.next();
			Relation relation = d.getRelationTo(next);
			switch(relation){
			case isChildOf: isDragging = false; return;
			case same: isDragging = false; return;
			}
		}
		i = selected.iterator();
		while(i.hasNext()){
			Duster<Color> next = i.next();
			if(d.getID() != next.getID() && !next.isRoot()){
				next.getParent().children.remove(next);
				d.addChild(next);
			}
		}
		clearSelection();
		app.drawer.initByMaxDev();
		isDragging = false;
	}

	public void keyPressed(PApplet pa) {
		// TODO Auto-generated method stub
		
	}

	public void mouseMoved(PApplet pa) {
		// TODO Auto-generated method stub
		
	}

	public void draw(PApplet pa) {
		// TODO Auto-generated method stub
		
	}
}
